package RPC;

import com.rabbitmq.client.*;
import constant.Constant;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.Host);
        connectionFactory.setPort(Constant.Port);
        connectionFactory.setUsername(Constant.userName);
        connectionFactory.setPassword(Constant.userName);
        connectionFactory.setVirtualHost(Constant.VirtualHost);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(Constant.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constant.RPC_RESPONSE_QUEUE,true,false,false,null);

        // 发送请求
        // 设置请求相关属性
        String msg = "这是一个RPC类型";
        String correlationId = UUID.randomUUID().toString();
        AMQP.BasicProperties properties = new AMQP.BasicProperties()
                .builder()
                .correlationId(correlationId) // 请求的唯一标识
                .replyTo(Constant.RPC_RESPONSE_QUEUE)
                .build();
        channel.basicPublish("",Constant.RPC_REQUEST_QUEUE,properties,msg.getBytes());

        // 接收响应,需要进行阻塞,存储响应信息
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String responseMsg = new String(body);
                System.out.println("接收到回调消息: "+responseMsg);
                if(correlationId.equals(properties.getCorrelationId())){
                    // 校验一致,是想要的响应
                    response.offer(responseMsg);
                }
            }
        };
        channel.basicConsume(Constant.RPC_RESPONSE_QUEUE,true,consumer);
        String result = response.take();
        System.out.println("RPC通信发送的信息为: "+result);

        channel.close();
        connection.close();
    }
}
